package com.example.View;

import com.example.AlertHelper;
import com.example.PO.Product;
import com.example.Service.ProductService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.util.List;

public class ProductView {
    private ProductService productService = new ProductService();
    private TableView<Product> tableView;
    private ObservableList<Product> productList;

    public ProductView() {
        // 创建表格视图
        tableView = new TableView<>();
        productList = FXCollections.observableArrayList(productService.getAllProducts());
        tableView.setItems(productList);

        // 定义表格列
        TableColumn<Product, Integer> idColumn = new TableColumn<>("产品编号");
        idColumn.setCellValueFactory(new PropertyValueFactory<>("screwId"));

        TableColumn<Product, String> nameColumn = new TableColumn<>("名称");
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));

        TableColumn<Product, String> materialColumn = new TableColumn<>("材质");
        materialColumn.setCellValueFactory(new PropertyValueFactory<>("material"));

        TableColumn<Product, String> diameterColumn = new TableColumn<>("直径");
        diameterColumn.setCellValueFactory(new PropertyValueFactory<>("diameter"));

        TableColumn<Product, String> lenthColumn = new TableColumn<>("长度");
        lenthColumn.setCellValueFactory(new PropertyValueFactory<>("lenth"));

        //=================================================================================
        TableColumn<Product, String> screw_typeColumn = new TableColumn<>("螺丝类型");
        screw_typeColumn.setCellValueFactory(new PropertyValueFactory<>("screw_type"));

        TableColumn<Product, String> top_typeColumn = new TableColumn<>("头部类型");
        top_typeColumn.setCellValueFactory(new PropertyValueFactory<>("top_type"));

        TableColumn<Product, String> weightColumn = new TableColumn<>("重量");
        weightColumn.setCellValueFactory(new PropertyValueFactory<>("weight"));

        TableColumn<Product, String> numberColumn = new TableColumn<>("数量");
        numberColumn.setCellValueFactory(new PropertyValueFactory<>("number"));

        TableColumn<Product, String> purchase_priceColumn = new TableColumn<>("进货单价");
        purchase_priceColumn.setCellValueFactory(new PropertyValueFactory<>("purchase_price"));

        TableColumn<Product, String> sale_priceColumn = new TableColumn<>("销售单价");
        sale_priceColumn.setCellValueFactory(new PropertyValueFactory<>("sale_price"));

        TableColumn<Product, String> total_purchaseColumn = new TableColumn<>("总进价");
        total_purchaseColumn.setCellValueFactory(new PropertyValueFactory<>("total_purchase"));
        //=================================================================================
        TableColumn<Product, String> total_saleColumn = new TableColumn<>("总售价");
        total_saleColumn.setCellValueFactory(new PropertyValueFactory<>("total_sale"));

        TableColumn<Product, String> vendorColumn = new TableColumn<>("供应商");
        vendorColumn.setCellValueFactory(new PropertyValueFactory<>("vendor"));

        tableView.getColumns().addAll(idColumn, nameColumn, materialColumn, diameterColumn, lenthColumn, screw_typeColumn, top_typeColumn, weightColumn, numberColumn, purchase_priceColumn, sale_priceColumn, total_purchaseColumn, total_saleColumn, vendorColumn);
        // 创建操作按钮
        Button addButton = new Button("添加产品");
        Button editButton = new Button("编辑产品");
        Button deleteButton = new Button("删除产品");
        Button refreshButton = new Button("刷新");

        // 按钮事件处理
        addButton.setOnAction(e -> showAddProductDialog());
        editButton.setOnAction(e -> showEditProductDialog());
        deleteButton.setOnAction(e -> deleteSelectedProduct());
        refreshButton.setOnAction(e -> refreshTable());

        // 按钮布局
        HBox buttonBox = new HBox(10);
        buttonBox.getChildren().addAll(addButton, editButton, deleteButton, refreshButton);

        // 搜索框
        TextField searchField = new TextField();
        searchField.setPromptText("请输入搜索内容");
        searchField.textProperty().addListener((observable, oldValue, newValue) -> filterTable(newValue));

        // 主布局
        VBox view = new VBox(20);
        view.getChildren().addAll(searchField, buttonBox, tableView);
    }

    public VBox getView() {
        VBox view = new VBox(20);
        TextField searchField = new TextField();
        searchField.setPromptText("请输入搜索内容");
        searchField.textProperty().addListener((observable, oldValue, newValue) -> filterTable(newValue));

        Button addButton = new Button("添加产品");
        Button editButton = new Button("编辑产品");
        Button deleteButton = new Button("删除产品");
        Button refreshButton = new Button("刷新");

        addButton.setOnAction(e -> showAddProductDialog());
        editButton.setOnAction(e -> showEditProductDialog());
        deleteButton.setOnAction(e -> deleteSelectedProduct());
        refreshButton.setOnAction(e -> refreshTable());

        HBox buttonBox = new HBox(10);
        buttonBox.getChildren().addAll(addButton, editButton, deleteButton, refreshButton);

        view.getChildren().addAll(searchField, buttonBox, tableView);
        return view;
    }

    private void showAddProductDialog() {
        Dialog<Product> dialog = new Dialog<>();
        dialog.setTitle("添加产品");
        dialog.setHeaderText("请输入产品信息");

        // 设置对话框按钮
        ButtonType addButtonType = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);

        // 创建输入字段
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);

        TextField nameField = new TextField();
        nameField.setPromptText("产品名称");
        TextField materialField = new TextField();
        materialField.setPromptText("材质");
        TextField diameterField = new TextField();
        diameterField.setPromptText("直径");
        TextField lenthField = new TextField();
        lenthField.setPromptText("长度");
        TextField screw_typeField = new TextField();
        screw_typeField.setPromptText("螺丝类型");
        TextField top_typeField = new TextField();
        top_typeField.setPromptText("头部类型");
        TextField weightField = new TextField();
        weightField.setPromptText("重量");
        TextField numberField = new TextField();
        numberField.setPromptText("数量");
        TextField purchase_priceField = new TextField();
        purchase_priceField.setPromptText("进价");
        TextField sale_priceField = new TextField();
        sale_priceField.setPromptText("售价");
        TextField total_purchaseField = new TextField();
        total_purchaseField.setPromptText("总进价");
        TextField total_saleField = new TextField();
        total_saleField.setPromptText("总售价");
        TextField vendorField = new TextField();
        vendorField.setPromptText("供应商");

        grid.add(new Label("产品名称:"), 0, 0);
        grid.add(nameField, 1, 0);
        grid.add(new Label("材质:"), 0, 1);
        grid.add(materialField, 1, 1);
        grid.add(new Label("直径:"), 0, 2);
        grid.add(diameterField, 1, 2);
        grid.add(new Label("长度:"), 0, 3);
        grid.add(lenthField, 1, 3);
        grid.add(new Label("螺丝类型:"), 0, 4);
        grid.add(screw_typeField, 1, 4);
        grid.add(new Label("头部类型:"), 0, 5);
        grid.add(top_typeField, 1, 5);
        grid.add(new Label("重量:"), 0, 6);
        grid.add(weightField, 1, 6);
        grid.add(new Label("数量:"), 0, 7);
        grid.add(numberField, 1, 7);
        grid.add(new Label("进价:"), 0, 8);
        grid.add(purchase_priceField, 1, 8);
        grid.add(new Label("售价:"), 0, 9);
        grid.add(sale_priceField, 1, 9);
        grid.add(new Label("总进价:"), 0, 10);
        grid.add(total_purchaseField, 1, 10);
        grid.add(new Label("总售价:"), 0, 11);
        grid.add(total_saleField, 1, 11);
        grid.add(new Label("供应商:"), 0, 12);
        grid.add(vendorField, 1, 12);


        dialog.getDialogPane().setContent(grid);


        // 转换结果
        dialog.setResultConverter(dialogButton -> {

            try {
                int number = Integer.parseInt(numberField.getText().trim());
                double purchase_price = Double.parseDouble(purchase_priceField.getText().trim());
                double sale_price = Double.parseDouble(sale_priceField.getText().trim());
                double total_purchase = number * purchase_price;
                double total_sale = number * sale_price;
                if (dialogButton == addButtonType) {
                    int newId = productList.size() + 1;
                    return new Product(newId, nameField.getText(), materialField.getText(), diameterField.getText(), lenthField.getText(), screw_typeField.getText(), top_typeField.getText(), weightField.getText(), number, purchase_price, sale_price, total_purchase, total_sale, vendorField.getText());
                }
                // 使用 number 进行后续操作
            } catch (NumberFormatException e) {
                // 处理无效输入（例如弹窗提示用户）
                System.err.println("请输入有效的整数！");
            }

            return null;
        });

        // 处理结果
        dialog.showAndWait().ifPresent(product -> {
            productService.addProduct(product);
            productList.add(product);
        });
    }

    private void showEditProductDialog() {
         Product selectedProduct = tableView.getSelectionModel().getSelectedItem();
        if (selectedProduct != null) {
            Dialog<Product> dialog = new Dialog<>();
            dialog.setTitle("编辑产品");
            dialog.setHeaderText("请修改产品信息");

            // 设置对话框按钮
            ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
            dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

            // 创建输入字段
            GridPane grid = new GridPane();
            grid.setHgap(10);
            grid.setVgap(10);

            TextField nameField = new TextField(selectedProduct.getName());
            nameField.setPromptText("产品名称");
            TextField materialField = new TextField(selectedProduct.getMaterial());
            materialField.setPromptText("材质");
            TextField diameterField = new TextField(selectedProduct.getDiameter());
            diameterField.setPromptText("直径");
            TextField lenthField = new TextField(selectedProduct.getLenth());
            lenthField.setPromptText("长度");
            TextField screw_typeField = new TextField(selectedProduct.getScrew_type());
            screw_typeField.setPromptText("螺丝类型");
            TextField top_typeField = new TextField(selectedProduct.getTop_type());
            top_typeField.setPromptText("头部类型");
            TextField weightField = new TextField(selectedProduct.getWeight());
            weightField.setPromptText("重量");
            TextField numberField = new TextField(String.valueOf(selectedProduct.getNumber()));
            numberField.setPromptText("数量");
            TextField purchase_priceField = new TextField(String.valueOf(selectedProduct.getPurchase_price()));
            purchase_priceField.setPromptText("进价");
            TextField sale_priceField = new TextField(String.valueOf(selectedProduct.getSale_price()));
            sale_priceField.setPromptText("售价");
            TextField total_purchaseField = new TextField(String.valueOf(selectedProduct.getTotal_purchase()));
            total_purchaseField.setPromptText("总进价");
            TextField total_saleField = new TextField(String.valueOf(selectedProduct.getTotal_sale()));
            total_saleField.setPromptText("总售价");
            TextField vendorField = new TextField(selectedProduct.getVendor());
            vendorField.setPromptText("供应商");



            grid.add(new Label("产品名称"), 0, 0);
            grid.add(nameField, 1, 0);
            grid.add(new Label("材质"), 0, 1);
            grid.add(materialField, 1, 1);
            grid.add(new Label("直径"), 0, 2);
            grid.add(diameterField, 1, 2);
            grid.add(new Label("长度"), 0, 3);
            grid.add(lenthField, 1, 3);
            grid.add(new Label("螺丝类型"), 0, 4);
            grid.add(screw_typeField, 1, 4);
            grid.add(new Label("头部类型"), 0, 5);
            grid.add(top_typeField, 1, 5);
            grid.add(new Label("重量"), 0, 6);
            grid.add(weightField, 1, 6);
            grid.add(new Label("数量"), 0, 7);
            grid.add(numberField, 1, 7);
            grid.add(new Label("进价"), 0, 8);
            grid.add(purchase_priceField, 1, 8);
            grid.add(new Label("售价"), 0, 9);
            grid.add(sale_priceField, 1, 9);
            grid.add(new Label("总进价"), 0, 10);
            grid.add(total_purchaseField, 1, 10);
            grid.add(new Label("总售价"), 0, 11);
            grid.add(total_saleField, 1, 11);
            grid.add(new Label("供应商"), 0, 12);
            grid.add(vendorField, 1, 12);

            dialog.getDialogPane().setContent(grid);

            // 转换结果
            dialog.setResultConverter(dialogButton -> {
                if (dialogButton == saveButtonType) {
                    selectedProduct.setName(nameField.getText());
                    selectedProduct.setMaterial(materialField.getText());
                    selectedProduct.setDiameter(diameterField.getText());
                    selectedProduct.setLenth(lenthField.getText());
                    selectedProduct.setScrew_type(screw_typeField.getText());
                    selectedProduct.setTop_type(top_typeField.getText());
                    selectedProduct.setWeight(weightField.getText());
                    selectedProduct.setNumber(Integer.parseInt(numberField.getText()));
                    selectedProduct.setPurchase_price(Double.parseDouble(purchase_priceField.getText()));
                    selectedProduct.setSale_price(Double.parseDouble(sale_priceField.getText()));
                    selectedProduct.setTotal_purchase(Double.parseDouble(total_purchaseField.getText()));
                    selectedProduct.setTotal_sale(Double.parseDouble(total_saleField.getText()));
                    selectedProduct.setVendor(vendorField.getText());
                    return selectedProduct;
                }
                return null;
            });

            // 处理结果
            dialog.showAndWait().ifPresent(product -> {
                productService.updateProduct(product);
                refreshTable();
            });
        }
    }

    private void deleteSelectedProduct() {
        Product selectedProduct = tableView.getSelectionModel().getSelectedItem();
        if (selectedProduct != null) {
            if (AlertHelper.showConfirmationDialog("确认删除", "确定要删除该产品信息吗？")) {
                productService.deleteProduct(selectedProduct.getScrewId());
                productList.remove(selectedProduct);
            }
        }
    }

    private void refreshTable() {
        productList.clear();
        productList.addAll(productService.getAllProducts());
    }

    private void filterTable(String keyword) {
        List<Product> allProducts = productService.getAllProducts();
        productList.clear();
        for (Product product : allProducts) {
            if (product.getName().contains(keyword) ||
                    product.getMaterial().contains(keyword) ||
                    product.getDiameter().contains(keyword) ||
                    product.getLenth().contains(keyword) ||
                    product.getScrew_type().contains(keyword) ||
                    product.getTop_type().contains(keyword) ||
                    product.getWeight().contains(keyword) ||
                    product.getVendor().contains(keyword))
            {
                productList.add(product);
            }
        }
    }
}